import { useState, useEffect } from 'react';

// 模拟用户角色和权限
const USER_ROLES = {
  ADMIN: 'admin',
  DOCTOR: 'doctor',
  NUTRITIONIST: 'nutritionist',
  TECH: 'tech',
};

// 角色权限映射
const ROLE_PERMISSIONS = {
  [USER_ROLES.ADMIN]: [
    'dashboard:view',
    'patients:*',
    'glucose:*',
    'diet:*',
    'devices:*',
    'reports:*',
    'settings:*',
  ],
  [USER_ROLES.DOCTOR]: [
    'dashboard:view',
    'patients:view',
    'patients:edit',
    'glucose:view',
    'glucose:edit',
    'diet:view',
    'reports:view',
    'devices:view',
  ],
  [USER_ROLES.NUTRITIONIST]: [
    'dashboard:view',
    'patients:view',
    'diet:*',
    'reports:view',
    'reports:generate',
  ],
  [USER_ROLES.TECH]: [
    'dashboard:view',
    'devices:*',
    'settings:view',
    'settings:logs',
  ],
};

// 模拟当前用户信息
const getCurrentUser = () => {
  const userStr = localStorage.getItem('user');
  return userStr ? JSON.parse(userStr) : null;
};

export const useAuth = () => {
  const [user, setUser] = useState(null);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    // 模拟获取用户信息
    const fetchUser = () => {
      const currentUser = getCurrentUser();
      setUser(currentUser);
      setLoading(false);
    };

    fetchUser();
  }, []);

  const login = async (username, password) => {
    // 模拟登录逻辑
    // 实际项目中这里会调用API验证用户
    const mockUser = {
      id: 1,
      username,
      role: USER_ROLES.ADMIN, // 默认为管理员角色
    };

    localStorage.setItem('user', JSON.stringify(mockUser));
    localStorage.setItem('access_token', 'mock-jwt-token');
    setUser(mockUser);
    return mockUser;
  };

  const logout = () => {
    localStorage.removeItem('user');
    localStorage.removeItem('access_token');
    setUser(null);
  };

  const hasPermission = (permission) => {
    if (!user || !user.role) return false;
    
    const permissions = ROLE_PERMISSIONS[user.role] || [];
    
    // 检查是否有完全匹配的权限
    if (permissions.includes(permission)) return true;
    
    // 检查是否有通配符权限
    const [resource] = permission.split(':');
    return permissions.includes(`${resource}:*`);
  };

  const hasRole = (role) => {
    return user && user.role === role;
  };

  return {
    user,
    loading,
    login,
    logout,
    hasPermission,
    hasRole,
  };
};
